package com.ruoyi.web.controller.union;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.flowable.common.constant.ProcessConstants;
import com.ruoyi.flowable.common.enums.FlowComment;
import com.ruoyi.flowable.service.ISysFormService;
import com.ruoyi.system.domain.ActReProcdef;
import com.ruoyi.system.domain.SysForm;
import com.ruoyi.system.service.IActReProcdefService;
import com.ruoyi.common.core.domain.entity.SysUser;
import org.flowable.engine.HistoryService;
import org.flowable.engine.IdentityService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.union.domain.SysActivity;
import com.ruoyi.union.domain.vo.SysActivityVo;
import com.ruoyi.union.service.ISysActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * 基层工会活动Controller
 *
 * @author ruoyi
 * @date 2025-01-15
 */
@RestController
@RequestMapping("/system/union/activity")
public class SysActivityController extends BaseController
{
    @Autowired
    private ISysActivityService sysActivityService;

    @Autowired
    private IActReProcdefService actReProcdefService;

    @Autowired
    private IdentityService identityService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private ISysFormService sysFormService;

    /**
     * 查询基层工会活动列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SysActivity sysActivity)
    {
        LambdaQueryWrapper<SysActivity> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotNull(sysActivity.getActivityName())) {
            wrapper.like(SysActivity::getActivityName, sysActivity.getActivityName());
        }
        if (StringUtils.isNotNull(sysActivity.getDeptId())) {
            wrapper.eq(SysActivity::getDeptId, sysActivity.getDeptId());
        }
        if (StringUtils.isNotNull(sysActivity.getPublisherId())) {
            wrapper.eq(SysActivity::getPublisherId, sysActivity.getPublisherId());
        }
        if (StringUtils.isNotNull(sysActivity.getActivityStatus())) {
            wrapper.eq(SysActivity::getActivityStatus, sysActivity.getActivityStatus());
        }
        if (StringUtils.isNotNull(sysActivity.getApprovalStatus())) {
            wrapper.eq(SysActivity::getApprovalStatus, sysActivity.getApprovalStatus());
        }
        startPage();
        List<SysActivityVo> list = sysActivityService.selectSysActivityVoList(sysActivity);
        return getDataTable(list);
    }

    /**
     * 导出基层工会活动列表
     */
    @PreAuthorize("@ss.hasPermi('union:activity:export')")
    @Log(title = "基层工会活动", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysActivity sysActivity)
    {
        LambdaQueryWrapper<SysActivity> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotNull(sysActivity.getActivityName())) {
            wrapper.like(SysActivity::getActivityName, sysActivity.getActivityName());
        }
        if (StringUtils.isNotNull(sysActivity.getDeptId())) {
            wrapper.eq(SysActivity::getDeptId, sysActivity.getDeptId());
        }
        if (StringUtils.isNotNull(sysActivity.getPublisherId())) {
            wrapper.eq(SysActivity::getPublisherId, sysActivity.getPublisherId());
        }
        if (StringUtils.isNotNull(sysActivity.getActivityStatus())) {
            wrapper.eq(SysActivity::getActivityStatus, sysActivity.getActivityStatus());
        }
        if (StringUtils.isNotNull(sysActivity.getApprovalStatus())) {
            wrapper.eq(SysActivity::getApprovalStatus, sysActivity.getApprovalStatus());
        }
        List<SysActivity> list = sysActivityService.list(wrapper);
        ExcelUtil<SysActivity> util = new ExcelUtil<>(SysActivity.class);
        util.exportExcel(response, list, "基层工会活动数据");
    }

    /**
     * 获取基层工会活动详细信息
     */
    @GetMapping(value = "/{activityId}")
    public AjaxResult getInfo(@PathVariable("activityId") Long activityId)
    {
        return success(sysActivityService.selectSysActivityByActivityId(activityId));
    }

    /**
     * 新增基层工会活动
     */
    @PreAuthorize("@ss.hasPermi('union:activity:add')")
    @Log(title = "基层工会活动", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysActivity sysActivity)
    {
        return toAjax(sysActivityService.insertSysActivity(sysActivity));
    }

    /**
     * 修改基层工会活动
     */
    @PreAuthorize("@ss.hasPermi('union:activity:edit')")
    @Log(title = "基层工会活动", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysActivity sysActivity)
    {
        return toAjax(sysActivityService.updateSysActivity(sysActivity));
    }

    /**
     * 删除基层工会活动
     */
    @PreAuthorize("@ss.hasPermi('union:activity:remove')")
    @Log(title = "基层工会活动", businessType = BusinessType.DELETE)
    @DeleteMapping("/{activityIds}")
    public AjaxResult remove(@PathVariable Long[] activityIds)
    {
        return toAjax(sysActivityService.deleteSysActivityByActivityIds(activityIds));
    }

    /**
     * 发布活动（发起审批流程）
     * 流程名称：活动发布审批
     */
    @PostMapping("/publishFlowable")
    public AjaxResult publishActivity(@RequestBody SysActivity sysActivity)
    {
        try {
            // 先保存活动信息
            boolean saved = sysActivityService.publishActivity(sysActivity);
            if (!saved) {
                return error("活动发布失败");
            }

            // 查询"活动发布审批"流程定义
            com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ActReProcdef> query = new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
            query.eq(ActReProcdef::getName, "基层工会活动");
            query.orderByDesc(ActReProcdef::getVersion);
            java.util.List<ActReProcdef> list = actReProcdefService.list(query);

            if (list != null && !list.isEmpty()) {
                // 启动流程实例
                java.util.HashMap<String, Object> variables = new java.util.HashMap<>();
                variables.put("commonClass", sysActivity);

                // 绑定表单（如有）
                SysForm form = new SysForm();
                form.setFormName("活动发布表单");
                java.util.List<SysForm> forms = sysFormService.selectSysFormList(form);
                if (forms.size() > 0) {
                    forms.sort(java.util.Comparator.comparing(SysForm::getFormId).reversed());
                    variables.put("formJson", forms.get(0).getFormContent());
                }

                SysUser user = SecurityUtils.getLoginUser().getUser();
                identityService.setAuthenticatedUserId(user.getUserId().toString());
                variables.put(ProcessConstants.PROCESS_INITIATOR, user.getUserId());

                ProcessInstance processInstance = runtimeService.startProcessInstanceById(list.get(0).getId(), variables);
                Task task = taskService.createTaskQuery().processInstanceId(processInstance.getProcessInstanceId()).singleResult();
                if (task != null) {
                    taskService.addComment(task.getId(), processInstance.getProcessInstanceId(), FlowComment.NORMAL.getType(), user.getNickName() + "发起活动发布审批");
                    taskService.complete(task.getId(), variables);
                }
            }
            return success("活动发布申请提交成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return error("活动发布申请提交失败");
    }

    /**
     * 审核活动
     */
    @PostMapping("/approve")
    public AjaxResult approveActivity(@RequestBody SysActivity sysActivity)
    {
        boolean result = sysActivityService.approveActivity(
            sysActivity.getActivityId(),
            sysActivity.getApprovalStatus(),
            null // 审核意见暂时设为null，因为SysActivity没有remark字段
        );
        return result ? success("审核成功") : error("审核失败");
    }

    /**
     * 根据部门ID查询活动列表
     */
    @GetMapping("/dept/{deptId}")
    public AjaxResult getActivitiesByDeptId(@PathVariable Long deptId)
    {
        return success(sysActivityService.selectSysActivityByDeptId(deptId));
    }

    /**
     * 根据发布人ID查询活动列表
     */
    @GetMapping("/publisher/{publisherId}")
    public AjaxResult getActivitiesByPublisherId(@PathVariable Long publisherId)
    {
        return success(sysActivityService.selectSysActivityByPublisherId(publisherId));
    }

    /**
     * 更新活动状态
     */
    @PostMapping("/updateStatus")
    public AjaxResult updateActivityStatus(@RequestBody SysActivity sysActivity)
    {
        boolean result = sysActivityService.updateActivityStatus(
            sysActivity.getActivityId(),
            sysActivity.getActivityStatus()
        );
        return result ? success("状态更新成功") : error("状态更新失败");
    }
}
